package org.easyspring.juc;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @description: ReentrantLock
 *   独占锁,默认非公平锁
 *   加锁次数和释放次数要保持一致
 *   加锁操作要放在try代码之前，释放锁放在finally中
 * @author：hy
 * @date: 2024/10/12
 */
public class ReentrantLockDemo {
    private final ReentrantLock lock = new ReentrantLock(true);//默认非公平
    private static int tickets = 8; // 总票数
    public void buyTicket(){
        //获取锁
        lock.lock();
        try {
            //还有票
            if (tickets > 0) {
                try {
                    //休眠10ms，模拟出并发效果
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "购买了第" + tickets-- + "张票");
            } else {
                System.out.println("票已经卖完了," + Thread.currentThread().getName() + "抢票失败");
            }
        }finally {
            //释放锁
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ReentrantLockDemo tickSystem =new ReentrantLockDemo();
        for (int i = 0; i <=10 ; i++) {
           Thread thread =new Thread(()->{
               //抢票
               tickSystem.buyTicket();
           });
           //启动线程
           thread.start();
        }
    }
}
